<?php
namespace app\api\controller\v1;
use think\Db;
use app\service\GaodeService;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
class Publics extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}

	/**
	 * 获取手机验证码
	 */
	public function get_mobile_code()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$validate = $this->validate(
			$params,
			[
				'mobile' => ['require', 'regex' => '^1((3|4|5|6|7|8|9){1}\d{1})\d{8}$']
			],
			[
				'mobile.require' => '请输入手机号',
				'mobile.regex' => '手机格式有误'
			]
		);
		if(true !== $validate)
		{
			echo json_encode(['code' => -1, 'msg' => $validate]);
			exit();
		}
		//验证码发送时间
		$send_time = time();
		$mobile_info = cache($params['mobile'].'_mobile_code');
		if(!empty($mobile_info))
		{
			//如果已经发送过
			$send_time = $mobile_info['send_time'];
		}
		//判断发送时间
		if(time() < $send_time)
		{
			echo json_encode(['code' => -1, 'msg' => '请'.($send_time - time()).'秒后重新发送']);
			exit();
		}
		$mobile_code = GetRandomStr(6, 'int');
//        Db::table('code')->insert(['code'=>$mobile_code]);
		//发送短信
		$res_sms = aliyun_send_sms("LTAI5tCfyuqK4o58i6MH3qH2","xXOnPRM4tMimqDVR4e1Ms5crn0lUtP",$params['mobile'],"太原合旭网络科技有限公司",'SMS_267295075',["code" => $mobile_code]);

		if($res_sms['Code'] == "OK")
		{
			cache($params['mobile'].'_mobile_code', ['mobile_code' => $mobile_code, 'send_time' => (time() + 60)], 600); //验证码有效期10分钟
			$result['code'] = 0;
			$result['msg'] = "短信发送成功";
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "短信发送失败";
		}
		echo json_encode($result);
	}

	/**
	 * 用户登录
	 */
	public function login()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$validate = $this->validate(
			$params,
			[
				'agreement' => 'require|eq:false',
				'mobile' => ['require','regex' => '^1((3|4|5|6|7|8|9){1}\d{1})\d{8}$'],
				'mobile_code' => 'require'
			],
			[
				'agreement.require' => '请同意协议',
				'agreement.eq' => '请同意协议',
				'mobile.require' => '请填写手机号',
				'mobile.regex' => '手机格式有误',
				'mobile_code.require' => '请填写验证码'
			]
		);
		if(true !== $validate){
			echo json_encode(['code' => -1, 'msg' => $validate]);
			exit();
		}
		//判断验证码是否正确
		$mobile_info = cache($params['mobile'].'_mobile_code');
        if ($params['mobile'] != 15035514195){
//        if ($params['mobile'] != 19135035059){
            if(empty($mobile_info))
            {
                echo json_encode(['code' => -1, 'msg' => '请重新获取验证码']);
                exit();
            }
            if($mobile_info['mobile_code'] != $params['mobile_code'])
            {
                echo json_encode(['code' => -1, 'msg' => '验证码不正确']);
                exit();
            }
        }

		cache($params['mobile'].'_mobile_code', NULL);
		$mobile = $params['mobile'];
		$user_info = Db::name('user')->where(['mobile' => $mobile])->find();
		//请求身份
		$identity_type = IdentityType();
		//当前应用平台
		$client_type = ApplicationClientType();
		//用户token
		$token = '';
		if(!empty($user_info))
		{
			//存在
			$user_id = $user_info['id'];
			//更新用户token
			$token = md5(md5($user_id.time()).rand(100, 1000000)).'_'.GetUserRecommendCode($user_id);
			// 启动事务
			Db::startTrans();
			//查询用户关联token是否存在
			$user_token_info = Db::name('user_token')->where(['user_id' => $user_id, 'identity_type' => $identity_type, 'client_type' => $client_type])->find();
			if(!empty($user_token_info))
			{
				//更新用户token
				if(!Db::name('user_token')->where(['id' => $user_token_info['id']])->update(['token' => $token, 'upd_time' => time()]))
				{
					//回滚事务
					Db::rollback();
					echo json_encode(['code' => -1, 'msg' => '登录失败1']);
					exit();
				}
			}else
			{
				//插入用户关联token
				$user_token_id = Db::name('user_token')->insertGetId([
					'user_id' => $user_id,
					'identity_type' => $identity_type,
					'client_type' => $client_type,
					'token' => $token,
					'add_time' => time(),
					'upd_time' => time()
				]);
				if($user_token_id <= 0)
				{
					//回滚事务
					Db::rollback();
					echo json_encode(['code' => -1, 'msg' => '登录失败2']);
					exit();
				}
			}

			//处理openid
			if(!empty($params['openid']))
			{
				//查询用户关联微信openid是否存在
				$user_weixin_info = Db::name('user_weixin')->where(['user_id' => $user_id, 'identity_type' => $identity_type, 'client_type' => $client_type])->find();
				if(!empty($user_weixin_info))
				{
					//更新用户微信openid
					if(!Db::name('user_weixin')->where(['id' => $user_weixin_info['id']])->update(['openid' => $params['openid'], 'upd_time' => time()]))
					{
						//回滚事务
						Db::rollback();
						echo json_encode(['code' => -1, 'msg' => '登录失败3']);
						exit();
					}
				}else
				{
					//插入用户关联微信openid表
					$user_weixin_id = Db::name('user_weixin')->insertGetId([
						'user_id' => $user_id,
						'identity_type' => $identity_type,
						'client_type' => $client_type,
						'openid' => $params['openid'],
						'add_time' => time(),
						'upd_time' => time()
					]);
					if($user_weixin_id <= 0)
					{
						//回滚事务
						Db::rollback();
						echo json_encode(['code' => -1, 'msg' => '登录失败4']);
						exit();
					}
				}
			}
			if(!empty($params['nickname']) || !empty($params['avatar']))
			{
				if(!Db::name('user')->where(['id' => $user_id])->update(['nickname' => $params['nickname'], 'avatar' => $params['avatar'], 'upd_time' => time()]))
				{
					//回滚事务
					Db::rollback();
					echo json_encode(['code' => -1, 'msg' => '登录失败5']);
					exit();
				}
			}
			//提交事务
			Db::commit();
		}else
		{
			//不存在
			//启动事务
			Db::startTrans();
			//插入用户主表
			$user_id = Db::name('user')->insertGetId([
				'mobile' => $mobile,
				'nickname' => !empty($params['nickname']) ? $params['nickname'] : '',
				'avatar' => !empty($params['avatar']) ? $params['avatar'] : '',
				'top_id' => $params['top_id'],
				'add_time' => time(),
				'upd_time' => time()
			]);
			if($user_id <= 0)
			{
				//回滚事务
				Db::rollback();
				echo json_encode(['code' => -1, 'msg' => '登录失败6']);
				exit();
			}
			//更新用户token
			$token = md5(md5($user_id.time()).rand(100, 1000000)).'_'.GetUserRecommendCode($user_id);
			//插入用户关联token
			$user_token_id = Db::name('user_token')->insertGetId([
				'user_id' => $user_id,
				'identity_type' => $identity_type,
				'client_type' => $client_type,
				'token' => $token,
				'add_time' => time(),
				'upd_time' => time()
			]);
			if($user_token_id <= 0)
			{
				//回滚事务
				Db::rollback();
				echo json_encode(['code' => -1, 'msg' => '登录失败7']);
				exit();
			}
			//插入用户关联微信openid表
			if(!empty($params['openid']))
			{
				$user_weixin_id = Db::name('user_weixin')->insertGetId([
					'user_id' => $user_id,
					'identity_type' => $identity_type,
					'client_type' => $client_type,
					'openid' => $params['openid'],
					'add_time' => time(),
					'upd_time' => time()
				]);
				if($user_weixin_id <= 0)
				{
					//回滚事务
					Db::rollback();
					echo json_encode(['code' => -1, 'msg' => '登录失败8']);
					exit();
				}
			}

			//提交事务
			Db::commit();
			//处理用户注册送优惠券
			//获取注册发放的优惠券
			$coupon_list = Db::name('coupon')->where('((expire_type = 0) or (expire_type = 1 and fixed_time_end > '.time().')) and send_scene = 1 and is_enable = 1 and is_delete_time = 0')->where('send_proxy','')->where('send_scene',1)->select();
			if(!empty($coupon_list))
			{
				//用户优惠券数据
				$coupon_user_data = [];
				foreach($coupon_list as $key => $value)
				{
					if(($value['limit_send_count'] == 0) || ($value['limit_send_count'] > 0 && $value['already_send_count'] < $value['limit_send_count']))
					{
						//单次发放数量
						$one_send_count = $value['one_send_count'];
						if($value['limit_send_count'] > 0)
						{
							$surplus = $value['limit_send_count']-$value['already_send_count'];
							$one_send_count = $surplus >= $value['one_send_count'] ? $value['one_send_count'] : $surplus;
						}
						//过期时间计算
						switch($value['expire_type'])
						{
							// 领取生效
				            case 0 :
				                $time_start = time();
				                $time_end = time()+(3600*$value['expire_hour']);
				            break;
				            // 固定日期
				            case 1 :
				                $time_start = $value['fixed_time_start'];
				                $time_end = $value['fixed_time_end'];
				            break;
						}
						for($i = 0; $i < $one_send_count; $i++)
						{
							$coupon_user_data[] = [
								'user_id'           => $user_id,
								'coupon_id'         => $value['id'],
								'name'              => $value['name'],
								'coupon_type'       => $value['coupon_type'],
								'discount_value'    => $value['discount_value'],
								'where_order_price' => $value['where_order_price'],
								'time_start'        => $time_start,
								'time_end'          => $time_end,
								'is_valid'          => 1,
								'add_time'          => time(),
								'upd_time'          => time()
							];
						}
					}
				}
				if(!empty($coupon_user_data))
				{
				    foreach($coupon_user_data as $key => $value)
					{
						// 开启事务
						Db::startTrans();
						//用户添加优惠券
						$coupon_user_id = Db::name('coupon_user')->insertGetId($value);
						if($coupon_user_id <= 0)
						{
							// 事务回滚
							Db::rollback();
							continue;
						}
						//更新优惠券已发放数量
						if(!Db::name('coupon')->where(['id' => $value['coupon_id']])->update(['already_send_count' => Db::raw('already_send_count+1')]))
						{
							// 事务回滚
							Db::rollback();
							continue;
						}
						// 提交事务
						Db::commit();
					}
				}
			}
		}
		if(!empty($token))
		{
			$result['code'] = 0;
		    $result['msg'] = "登录成功";
		    $result['data'] = [
		    	'token' => $token
		    ];
		}else
		{
			$result['code'] = -1;
			$result['msg'] = "登录失败9";
		}
		echo json_encode($result);
	}

	/**
	 * 上传图片
	 */
	public function upload_images()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'path' => 'require'
			],
			[
				'path.require' => '上传路径不能为空'
			]
		);
		if(true !== $validate)
		{
			echo json_encode(['code' => -1, 'msg' => $validate]);
			exit();
		}
		if($file = request()->file('file'))
		{
			$info = $file->validate(['size'=>15678000,'ext'=>'jpg,png,gif,jpeg'])->move('./uploads/images/'.$params['path'].'/');
			if(!empty($info))
			{
				$url = '/uploads/images/'.$params['path'].'/'.str_replace('\\', '/', $info->getSaveName());
				$result['code'] = 0;
				$result['msg'] = '上传成功';
				$result['data'] = [
					'url' => $url
				];
			}else
			{
				$result['code'] = -1;
				$result['msg'] = $file->getError();
			}
		}else
		{
			$result['code'] = -1;
			$result['msg'] = "没有上传文件";
		}
		echo json_encode($result);
	}

	/**
	 * 坐标换取地址信息
	 */
	public function loc_get_address()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'lng' => 'require',
				'lat' => 'require'
			],
			[
				'lng.require' => '坐标有误',
				'lat.require' => '坐标有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //获取高德解地址
        $ni_dili_data = http_curl('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$params['lng'].','.$params['lat'].'&key='.GaodeService::$web_api_key);
        $ni_dili_data = json_decode($ni_dili_data, true);
        if($ni_dili_data['status'] == 1)
        {
            $qu_code = $ni_dili_data['regeocode']['addressComponent']['adcode'];
            $qu_info = Db::name('proxy')->where('qu',$qu_code)->find();
            if (!empty($qu_info)){
                $area_info = Db::name('area')->where(['id' => $qu_code, 'is_enable' => 1])->find();
                if(!empty($area_info))
                {
                    $result['code'] = 0;
                    $result['msg'] = "请求成功";
                    $result['data'] = $area_info;
                }else
                {
                    $result['code'] = -1;
                    $result['msg'] = "暂无数据";
                }
            }else{
                $citycode = $ni_dili_data['regeocode']['addressComponent']['citycode'];
                if(!empty($citycode))
                {
                    //查询当前城市
                    $area_info = Db::name('area')->where(['lev' => 2, 'city_code' => $citycode, 'is_enable' => 1])->find();
                    if(!empty($area_info))
                    {
                        $result['code'] = 0;
                        $result['msg'] = "请求成功";
                        $result['data'] = $area_info;

                    }else
                    {
                        $result['code'] = -1;
                        $result['msg'] = "暂无数据";
                    }
                }
            }
        }
        echo json_encode($result);
	}

	/**
	 * 获取微信公众号code
	 */
	public function wx_gzh_authorize_code()
	{
		$params = input();
		if(!empty($params['code']))
		{
			//dump($params);
			//获取code跳回登录页面
			$this->redirect(request()->domain().'/h5/pages/login/login?wx_gzh_code='.$params['code']);
		}else
		{
			$redirect_url = request()->url(true);
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".UserWeixinService::$web_appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			$this->redirect($url);
		}
	}

	/**
	 * 通过code获取微信信息
	 */
	public function wx_gzh_authorize_info()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$validate = $this->validate(
			$params,
			[
				'wx_gzh_code' => 'require'
			],
			[
				'wx_gzh_code.require' => '授权信息有误请重试'
			]
		);
		if(true !== $validate)
		{
			echo json_encode(['code' => -1, 'msg' => $validate]);
			exit();
		}
		$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".UserWeixinService::$web_appid."&secret=".UserWeixinService::$web_appsecret."&code=".$params['wx_gzh_code']."&grant_type=authorization_code";
		$access_token_res = http_curl($access_token_url);
		$access_token_res = json_decode($access_token_res,true);


		//dump($access_token_res);
		if(empty($access_token_res['access_token']))
		{


			echo json_encode(['code' => -1, 'msg' => '登录中,请稍等']);
			exit();
		}
		if(empty($access_token_res['openid']))
		{
			echo json_encode(['code' => -1, 'msg' => '授权信息有误请重试']);
			exit();
		}
		$access_token = $access_token_res['access_token'];
		$openid = $access_token_res['openid'];
		$wx_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		$wx_user_info = http_curl($wx_user_info_url);
		$wx_user_info = json_decode($wx_user_info,true);
        $insert = [
            'open_id'=>$wx_user_info['openid'],
            'add_time'=>time(),
        ];
//        Db::name('openid')->insert($insert);
		if(empty($wx_user_info['openid']))
		{
			echo json_encode(['code' => -1, 'msg' => '授权信息有误请重试']);
			exit();
		}
		//dump($wx_user_info);
		//请求身份
		$identity_type = IdentityType();
		//当前应用平台
		$client_type = ApplicationClientType();
		//查询用户关联微信openid是否存在
		$user_weixin_info = Db::name('user_weixin')->where(['identity_type' => $identity_type, 'client_type' => $client_type, 'openid' => $wx_user_info['openid']])->find();
		//判断openid是否存在
		$is_exist = 0; //0不存在、1存在
		if(empty($user_weixin_info))
		{
			//不存在
			$wx_user_info['is_exist'] = 0;
			$result['code'] = 0;
		    $result['msg'] = "success";
		    $result['data'] = $wx_user_info;
		}else
		{
			//存在
			$user_id = $user_weixin_info['user_id'];
			//更新用户token
			$token = md5(md5($user_id.time()).rand(100, 1000000)).'_'.GetUserRecommendCode($user_id);
			//查询用户关联token是否存在
			$user_token_info = Db::name('user_token')->where(['user_id' => $user_id, 'identity_type' => $identity_type, 'client_type' => $client_type])->find();
			//更新用户token
			if(!Db::name('user_token')->where(['id' => $user_token_info['id']])->update(['token' => $token, 'upd_time' => time()]))
			{
				echo json_encode(['code' => -1, 'msg' => '登录失败']);
				exit();
			}
			$result['code'] = 0;
		    $result['msg'] = "success";
		    $result['data'] = [
		    	'token' => $token,
		    	'is_exist' => 1
		    ];
		}
		echo json_encode($result);
	}

	/**
	 * 获取定位信息
	 */
	public function locate_info()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'lng' => 'require',
				'lat' => 'require'
			],
			[
				'lng.require' => '坐标有误',
				'lat.require' => '坐标有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //获取高德解地址
        $ni_dili_data = http_curl('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$params['lng'].','.$params['lat'].'&key='.GaodeService::$web_api_key);
        $ni_dili_data = json_decode($ni_dili_data, true);

        if($ni_dili_data['status'] != 1)
        {
        	echo json_encode(['code' => -1, 'msg' => '定位失败']);
            exit();
        }
        $result['code'] = 0;
		$result['msg'] = "请求成功";
		$result['data'] = [
			'formatted_address' => $ni_dili_data['regeocode']['formatted_address']
		];
		echo json_encode($result);
	}

	/**
	 * 公众号跳转小程序链接
	 */
	public function go_mini_app()
	{
		$params = input();
		if(!empty($params['code']))
		{
			//dump($params);
			$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".UserWeixinService::$web_appid."&secret=".UserWeixinService::$web_appsecret."&code=".$params['code']."&grant_type=authorization_code";
		    $access_token_res = http_curl($access_token_url);
		    $access_token_res = json_decode($access_token_res,true);
		    $openid = $access_token_res['openid'];
			//通过openid查找用户是否授权过
			$user_weixin_info = Db::name('user_weixin')->where(['identity_type' => 'user', 'client_type' => 'h5', 'openid' => $openid])->find();
			//dump($user_weixin_info);
			if(empty($user_weixin_info))
			{
				$this->redirect(request()->domain().'/h5/pages/login/login');
			}else
			{
				//获取技师端小程序跳转路径
				$url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token='.TechnWeixinService::get_mini_access_token();
				$mini_data = [
					'jump_wxa' => [
						'path' => 'pages/my/my',
						'env_version' => 'release'
					]
				];
				$mini_res = http_curl($url,json_encode($mini_data));
				$mini_res = json_decode($mini_res,true);
				if($mini_res['errcode'] == 0)
				{
					$this->redirect($mini_res['openlink']);
				}
			}
		}else
		{
			$redirect_url = request()->url(true);
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".UserWeixinService::$web_appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			$this->redirect($url);
		}
	}
}